# 数字保留两位小数
def format2_number(number):
    return '{:.2f}'.format(number)

# 金额元转换为万
def amount_w(number):
    return float(number) / 10000

# 等额本息每月还款金额计算方式
def get_mount_amount(amount, year_count, lpr):
    # 贷款月数
    month_count = year_count * 12
    # 贷款本金
    loan = amount
    # lpr 利率
    year_lpr = lpr / 100
    # lpr 月利率
    month_lpr = year_lpr / 12
    # 系数 (1+月利率)^还款月数
    t_lpr = (1 + month_lpr) ** month_count

    # 被除数 月利率 X (1 + 月利率) ^ 还款月数
    dividend = month_lpr * t_lpr
    # 除数 (1 + 月利率) ^ 还款月数 - 1
    divisor = t_lpr - 1
    # print('被除数 dividend', dividend)
    # print('除数 divisor', divisor)
    # 每月还款额=贷款本金×[月利率×(1+月利率)^还款月数]÷{[(1+月利率)^还款月数]-1}]
    month_amount = loan * dividend / divisor
    # print('每月还款金额：', format2_number(month_amount))
    total_amout = month_amount * month_count
    print('总还款金额(单位w):', format2_number(amount_w(total_amout)))
    total_rate = format2_number(total_amout - loan)
    print('总利息(单位w):', format2_number(amount_w(total_rate)))
    # 每月偿还利息 = 剩余本金 × 月利率
    first_amount = loan * month_lpr
    print('第一月利息:', format2_number(first_amount))
    # todo 每月偿还本金 = 每月还款额 - 每月还款利息
    return month_amount

def get_remain_amount_income(amount, year_count, rate, month_amount):
    # 贷款时，可利用金额
    available_amount = 0
    # 剩余还款金额，初始等于贷款金额
    repayment_amount = amount
    # 剩余还款年数
    remain_yarn = year_count

    while (repayment_amount > 0):
        # 减去每年还款金额
        repayment_amount -= month_amount * 12
        if repayment_amount > 0:
            # 除掉还款金额可用金额累计
            available_amount += repayment_amount
            remain_yarn -= 1

    print('可利用金额 (单位w):', format2_number(amount_w(available_amount)))

    # 年化收益
    interest_rate = rate / 100
    total_income = format2_number(available_amount * interest_rate)
    print('可利用金额收益年化' + '{:.2%}'.format(interest_rate) + '(单位w):', format2_number(amount_w(total_income)))
    return total_income

# 贷款本金
loan_amount = 20 * 10000
# 贷款年数
year_count = 10
# lpr
lpr = 4.2

month_amount = get_mount_amount(loan_amount, year_count, lpr)
print('每月还款金额：', format2_number(month_amount))

# 预计年化收益率
year_rate = 3
get_remain_amount = get_remain_amount_income(loan_amount, year_count, year_rate, month_amount)

